package com.mingmen.canting.gongyingshang;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.mingmen.canting.R;
import com.mingmen.canting.adapter.SearchSupplierAdapter;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.defineview.ClearEditText;
import com.mingmen.canting.defineview.GlideRoundTransform;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.AppConfig;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.immersionbar.ImmersionBar;
import com.mingmen.canting.model.GongYIngCateGoryModel;
import com.mingmen.canting.model.SupplierModel;
import com.mingmen.canting.model.SupplierSearchModel;
import com.mingmen.canting.popwindow.PopupWindowCompat;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.SharePreferenceUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class SupplierShopActivity extends FragmentActivity {
    @BindView(R.id.text_return)
    TextView textReturn;
    @BindView(R.id.linear_return)
    LinearLayout linearReturn;
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.mToolbar)
    Toolbar mToolbar;


    ShopFragment shopFragment;
    CommentFragment refreshPracticeFragment;
    ShangJiaFragment refreshStylesFragment;

    SheDingFragment sheDingFragment;


    @BindView(R.id.layout_shop)
    LinearLayout layout_shop;
    @BindView(R.id.layout_comment)
    LinearLayout layout_comment;
    @BindView(R.id.layout_shangjia)
    LinearLayout layout_shangjia;
    @BindView(R.id.layout_sheding)
    LinearLayout layout_sheding;
    @BindView(R.id.view_shop)
    View view_shop;
    @BindView(R.id.view_comment)
    View view_comment;
    @BindView(R.id.view_shangjia)
    View view_shangjia;
    @BindView(R.id.view_sheding)
    View view_sheding;

    String supplierId;
    String token;
    @BindView(R.id.supplierName)
    TextView supplierName;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.category)
    TextView category;
    @BindView(R.id.status)
    TextView status;
    @BindView(R.id.quantity)
    TextView quantity;
    @BindView(R.id.announcement)
    TextView announcement;

    @BindView(R.id.ivAvatar)
    ImageView ivAvatar;
    String logo;
    Context mContext;
    @BindView(R.id.layout_search_all)
    LinearLayout layout_search_all;
    @BindView(R.id.main_search)
    ClearEditText main_search;
    @BindView(R.id.layout_search)
    LinearLayout layout_search;
    String tel;
    @BindView(R.id.text_Phone)
    TextView text_Phone;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_supplier);
        ButterKnife.bind(this);
        textCenter.setText("合作供应商");
        ImmersionBar.with(this).titleBar(mToolbar)
                .navigationBarColor(R.color.black).init();

        mContext = this;
        token = (String) SharePreferenceUtil.get(this, "token", "");
        supplierId = getIntent().getStringExtra("supplierId");
        Log.d("supplierId", supplierId);
        SharePreferenceUtil.put(SupplierShopActivity.this, "supplierId", supplierId);
        getSupplier(token, supplierId);
        initFragment1();
        main_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

//                getSearch();
                //以下方法防止两次发送请求
                if (actionId == EditorInfo.IME_ACTION_SEND ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            //发送请求
                            String keyWord = main_search.getText().toString().trim();

                            keyWord = "";
                            popupWindow = new PopupWindowCompat(SupplierShopActivity.this);
                            View contentView = LayoutInflater.from(SupplierShopActivity.this).inflate(R.layout.pop_supplier_search, null);
                            popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                            popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                            popupWindow.setContentView(contentView);
                            popupWindow.setOutsideTouchable(true);
                            popupWindow.setFocusable(true);
                            popupWindow.setBackgroundDrawable(new BitmapDrawable());
                            LinearLayout layout_content = contentView.findViewById(R.id.layout_content);
//                    layout_content.getBackground().setAlpha(180);
                            SwipeRecyclerView recyclerView = contentView.findViewById(R.id.recycler_view);
                            recyclerView.setLayoutManager(new LinearLayoutManager(SupplierShopActivity.this));
                            myLabelAdapter = new SearchSupplierAdapter(SupplierShopActivity.this, dataBeanList1);
                            recyclerView.setAdapter(myLabelAdapter);
                            getSearch();

                            return true;
                        default:
                            return true;
                    }
                }

                return false;
            }
        });

    }

    List<GongYIngCateGoryModel.DataBean> dataBeanList = new ArrayList<>();
    SearchSupplierAdapter myLabelAdapter;
    PopupWindow popupWindow;
    List<SupplierSearchModel.DataBean> dataBeanList1 = new ArrayList<>();

    public void getSearch() {
        HttpResponse.listSupplierByKeyword(token, main_search.getText().toString(), new StringCallback(SupplierShopActivity.this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (dataBeanList.size() > 0) {
                    dataBeanList.clear();
                }

                SupplierSearchModel supplierSearchModel = new SupplierSearchModel();
                supplierSearchModel = GsonUtil.GsonToBean(s, SupplierSearchModel.class);
                dataBeanList1.addAll(supplierSearchModel.getData());
                if (dataBeanList1.size() > 0) {
                    InputMethodManager imm = (InputMethodManager)
                            SupplierShopActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);

                    myLabelAdapter.setDataList(dataBeanList1);

                    popupWindow.showAsDropDown(layout_search);
                    myLabelAdapter.setOnItemClickListener(new SearchSupplierAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClickListener(View view, int pos, List<SupplierSearchModel.DataBean> myLiveList) {
                            myLabelAdapter.setCheckedPosition(pos);
                            main_search.setText(myLiveList.get(pos).getName());
                            popupWindow.dismiss();
                            getSupplier(token, myLiveList.get(pos).getId());
                        }
                    });
                } else {
                    Toast.makeText(SupplierShopActivity.this, "当前搜索无数据", Toast.LENGTH_SHORT).show();
                }


            }
        });
    }


    public void getSupplier(String token, String supplierId) {
        HttpResponse.getSupplier(token, supplierId, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("SUpplisrShop", s);
                SupplierModel supplierModel = new SupplierModel();
                supplierModel = GsonUtil.GsonToBean(s, SupplierModel.class);
                supplierName.setText("名称: " + supplierModel.getData().get(0).getSupplierName());
                address.setText("地址: " + supplierModel.getData().get(0).getAddress());
                category.setText("分类: " + supplierModel.getData().get(0).getCategory());
                if (supplierModel.getData().get(0).getCooperation().equals("0")) {
                    status.setText("状态: 未合作");
                } else {
                    status.setText("状态: 已合作");
                }
                quantity.setText("默认商品: (" + supplierModel.getData().get(0).getQuantity() + ")");
                announcement.setText("公告:" + supplierModel.getData().get(0).getAnnouncement() + "");
                SharePreferenceUtil.put(SupplierShopActivity.this, "blackList", supplierModel.getData().get(0).getBlackList());
                SharePreferenceUtil.put(SupplierShopActivity.this, "addressStr", supplierModel.getData().get(0).getAddress());

                SharePreferenceUtil.put(SupplierShopActivity.this, "categoryStr", supplierModel.getData().get(0).getCategory());
                SharePreferenceUtil.put(SupplierShopActivity.this, "cooperation", supplierModel.getData().get(0).getCooperation());
                SharePreferenceUtil.put(SupplierShopActivity.this, "shippingFee", supplierModel.getData().get(0).getShippingFee() + "");
                Glide.with(mContext).load(AppConfig.IMGURL + supplierModel.getData().get(0).getPicture()).dontAnimate().placeholder(R.mipmap.zhanwei).error(R.mipmap.zhanwei).transform(new GlideRoundTransform(mContext, 5)).into(ivAvatar);
                tel = supplierModel.getData().get(0).getTel();
            }
        });
    }


    //显示第一个fragment
    private void initFragment1() {
        //开启事务，fragment的控制是由事务来实现的
        layout_search_all.setVisibility(View.VISIBLE);
        view_shop.setVisibility(View.VISIBLE);
        view_comment.setVisibility(View.INVISIBLE);
        view_shangjia.setVisibility(View.INVISIBLE);
        view_sheding.setVisibility(View.INVISIBLE);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (shopFragment == null) {
            shopFragment = new ShopFragment();
            transaction.add(R.id.main_frame_layout, shopFragment);
        }
        //隐藏所有fragment
        hideFragment(transaction);
        //显示需要显示的fragment
        transaction.show(shopFragment);
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (shopFragment != null) {
            transaction.hide(shopFragment);
        }
        if (refreshPracticeFragment != null) {
            transaction.hide(refreshPracticeFragment);
        }
        if (refreshStylesFragment != null) {
            transaction.hide(refreshStylesFragment);
        }
        if (sheDingFragment != null) {
            transaction.hide(sheDingFragment);
        }
    }

    //显示第二个fragment
    private void initFragment2() {
      /*  FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (refreshPracticeFragment == null) {
            refreshPracticeFragment = new CommentFragment();
        }
        transaction.replace(R.id.main_frame_layout, refreshPracticeFragment);

        transaction.commit();*/
        layout_search_all.setVisibility(View.GONE);
        view_shop.setVisibility(View.INVISIBLE);
        view_comment.setVisibility(View.VISIBLE);
        view_shangjia.setVisibility(View.INVISIBLE);
        view_sheding.setVisibility(View.INVISIBLE);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (refreshPracticeFragment == null) {
            refreshPracticeFragment = new CommentFragment();
            transaction.add(R.id.main_frame_layout, refreshPracticeFragment);
        }
        //隐藏所有fragment
        hideFragment(transaction);
        //显示需要显示的fragment
        transaction.show(refreshPracticeFragment);
        transaction.commit();
    }

    //显示第三个fragment
    private void initFragment3() {
      /*  FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (refreshStylesFragment == null) {
            refreshStylesFragment = new ShangJiaFragment();
        }
        transaction.replace(R.id.main_frame_layout, refreshStylesFragment);
        transaction.commit();*/
        layout_search_all.setVisibility(View.GONE);
        view_shop.setVisibility(View.INVISIBLE);
        view_comment.setVisibility(View.INVISIBLE);
        view_shangjia.setVisibility(View.VISIBLE);
        view_sheding.setVisibility(View.INVISIBLE);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (refreshStylesFragment == null) {
            refreshStylesFragment = new ShangJiaFragment();
            transaction.add(R.id.main_frame_layout, refreshStylesFragment);
        }
        //隐藏所有fragment
        hideFragment(transaction);
        //显示需要显示的fragment
        transaction.show(refreshStylesFragment);
        transaction.commit();
    }

    //显示第三个fragment
    private void initFragment4() {
     /*   FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (sheDingFragment == null) {
            sheDingFragment = new SheDingFragment();
        }
        transaction.replace(R.id.main_frame_layout, sheDingFragment);
        transaction.commit();*/
        layout_search_all.setVisibility(View.GONE);
        view_shop.setVisibility(View.INVISIBLE);
        view_comment.setVisibility(View.INVISIBLE);
        view_shangjia.setVisibility(View.INVISIBLE);
        view_sheding.setVisibility(View.VISIBLE);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (sheDingFragment == null) {
            sheDingFragment = new SheDingFragment();
            transaction.add(R.id.main_frame_layout, sheDingFragment);
        }
        //隐藏所有fragment
        hideFragment(transaction);
        //显示需要显示的fragment
        transaction.show(sheDingFragment);
        transaction.commit();
    }

    @OnClick({R.id.layout_shop, R.id.layout_comment, R.id.layout_shangjia, R.id.layout_sheding, R.id.text_return, R.id.linear_return, R.id.text_center, R.id.img_right, R.id.text_Phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.text_return:
                finish();
                break;
            case R.id.linear_return:
                finish();
                break;
            case R.id.text_center:
                break;
            case R.id.img_right:
                break;
            case R.id.layout_shop:
                initFragment1();
                break;
            case R.id.layout_comment:
                initFragment2();
                break;
            case R.id.layout_shangjia:
                initFragment3();
                break;
            case R.id.layout_sheding:
                initFragment4();
                break;
            case R.id.text_Phone:
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + tel);
                intent.setData(data);
                startActivity(intent);
                break;
        }
    }


}
